﻿#region ... Copyright Notice ...
/*
   Copyright 2008 Tyler Jensen

	Author: Tyler Jensen    http://www.tsjensen.com/blog

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
#endregion

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Xml.Linq;
using Atrax.Contracts;
using Atrax.Library;
using Atrax.Logging;

namespace Atrax.Master
{
	internal class Emailer
	{
		//<add key="NotificationFromEmail" value="atrax@netbrick.net" />
		//<add key="SmtpServer" value="smtp.netbrick.net" />
		//<add key="SmtpAuthenticationRequired" value="true" />
		//<add key="SmtpUsername" value="atrax@netbrick.net" />
		//<add key="SmtpPassword" value="atrax08" />

		internal void SendCallbackFailureNotification(QueryResult result, Exception exception)
		{
			try
			{
				string smtpServer = ConfigurationManager.AppSettings["smtpServer"];
				string smtpUsername = ConfigurationManager.AppSettings["smtpUsername"];
				string smtpPassword = ConfigurationManager.AppSettings["smtpPassword"];
				bool requiresAuthentication = ConfigurationManager.AppSettings["smtpAuthenticationRequired"].ToLower() == "true";
				string fromEmail = ConfigurationManager.AppSettings["notificationFromEmail"];
				string toEmail = result.Query.Header.NotificationEmail;
				string subject = "Atrax Callback Failure for QueryId " + result.Query.Header.QueryId;
				StringBuilder sb = new StringBuilder();
				sb.AppendLine("callbackerror=" + exception.ToString().Replace("\n", "").Replace("\r", " :: "));
				sb.AppendLine("");
				sb.AppendLine("queryid=" + result.Query.Header.QueryId);
				sb.AppendLine("clientqueryid=" + result.Query.Header.ClientQueryId);
				sb.AppendLine("jobtype=" + result.Query.Header.QueryType);
				sb.AppendLine("licensekeylastfive=" + result.Query.Header.LicenseKey.Substring(result.Query.Header.LicenseKey.Length - 5, 5));
				sb.AppendLine("priority=" + result.Query.Header.Priority.ToString());
				sb.AppendLine("statuscode=" + result.StatusCode);
				sb.AppendLine("statusdescription=" + result.StatusDescription.Replace("\n", "").Replace("\r", " :: "));
				sb.AppendLine("");
				string body = sb.ToString();
				MailMessage msg = new MailMessage(fromEmail, toEmail, subject, body);
				msg.IsBodyHtml = false;
				SmtpClient client = new SmtpClient(smtpServer);
				if (requiresAuthentication)
				{
					client.UseDefaultCredentials = false;
					client.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
				}
				client.Send(msg);
			}
			catch (Exception e)
			{
				Log.App(LogEvents.EmailerSendNotificationFailed, "queryid=" + result.Query.Header.QueryId
					+ " | querytype=" + result.Query.Header.QueryType + " | licensekey=" + result.Query.Header.LicenseKey, e);
			}
		}

		delegate void SendEmailAsynchDelegate(string toEmail, string subject, string body);

		internal void SendQueryExpiredNotification(Query query)
		{
			string toEmail = query.Header.NotificationEmail;
			string subject = "Atrax query timed out: " + query.Header.QueryId;
			string body = "QueryId " + query.Header.QueryId + " timed out and has been removed from the system. It is suggested that you review the original job request and resubmit.";
			SendEmailAsynchDelegate del = new SendEmailAsynchDelegate(SendEmailAsynch);
			del.BeginInvoke(toEmail, subject, body, null, null); //no callback required -- just tries on its own to launch
		}

		void SendEmailAsynch(string toEmail, string subject, string body)
		{
			try
			{
				string smtpServer = ConfigurationManager.AppSettings["smtpServer"];
				string smtpUsername = ConfigurationManager.AppSettings["smtpUsername"];
				string smtpPassword = ConfigurationManager.AppSettings["smtpPassword"];
				bool requiresAuthentication = ConfigurationManager.AppSettings["smtpAuthenticationRequired"].ToLower() == "true";
				string fromEmail = ConfigurationManager.AppSettings["notificationFromEmail"];
				MailMessage msg = new MailMessage(fromEmail, toEmail, subject, body);
				msg.IsBodyHtml = false;
				SmtpClient client = new SmtpClient(smtpServer);
				if (requiresAuthentication)
				{
					client.UseDefaultCredentials = false;
					client.Credentials = new NetworkCredential(smtpUsername, smtpPassword);
				}
				client.Send(msg);
			}
			catch(Exception e)
			{
				Log.App(LogEvents.EmailerSendEmailAsynchFailed, "to=" + toEmail + " | subject=" + subject, e);
			}
		}
	}
}
